//
//  UserAccount.swift
//  weibo_swift
//
//  Created by dulinlong on 15/6/28.
//  Copyright © 2015年 sheji_56. All rights reserved.
//

import UIKit

//1.2 Printal
//CustomStringConvertible
class UserAccount: NSObject, NSCoding {

    /// 用于调用access_token，接口获取授权后的access token。
    var access_token: String
    /// access_token的生命周期，单位是秒数。
    var expires_in: NSTimeInterval
    /// token过期日期
    var expiresDate: NSDate
    /// 当前授权用户的UID。
    var uid:String
    
    ///友好显示名称
    var name:String?
    ///用户头像地址（大图），180×180像素
    var avatar_large:String?
    
    init(dict: [String: AnyObject]){
     
        access_token = dict["access_token"] as! String
        expires_in = dict["expires_in"] as! NSTimeInterval
        uid = dict["uid"] as! String
        
        //计算过期日期
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        
    }
    
   override var description: String {
    
    let properties = ["access_token","expires_in","expiresDate","uid"]
    return "\(self.dictionaryWithValuesForKeys(properties))"
    }
    
    ///  网络获取用户信息
    func loadUserInfo(finished:(account:UserAccount?,error:NSError?) -> ()){
        
        let parameters = ["access_token":access_token,"uid":uid]
        
        NetWorkTool.sharedNetWorkTool().GET("2/users/show.json", parameters: parameters, success: { (_, JSON) -> Void in
            
            //赋值用户信息
            let dict = JSON as! [String:AnyObject]
            self.name = dict["name"] as? String
            self.avatar_large = dict["avatar_large"] as? String
            
            //保存用户信息
            self.saveAcount()
            
            //通知调用方,处理完成
            finished(account: self, error: nil)
            
            }) { (_, error) -> Void in
            finished(account: nil, error: error)
        }
    }
    
    ///  沙盒路径
    static let filePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingPathComponent("account.plist")
    
    ///  将用户信息保存在沙盒下
    func saveAcount(){
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.filePath!)
    }
    
    /// 从沙盒加载用户信息
    class func loadAccount() -> UserAccount?{
        //判断账户是剖过期
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath!) as? UserAccount{
            //如果没有过期
            if account.expiresDate.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                return account
            }
        }
        
        return nil
    }
    
    required init?(coder aDecoder: NSCoder){
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as! NSDate
        uid = aDecoder.decodeObjectForKey("uid") as! String
        
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        
    }
    
    func encodeWithCoder(aCoder: NSCoder){
        aCoder.encodeObject(access_token,forKey:"access_token")
        aCoder.encodeDouble(expires_in, forKey:"expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey:"uid")
        
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    
    
}
